import { Empty, Popover, Spin, Tree } from 'antd';
import { useCallback, useContext, useEffect, useMemo, useState } from 'react';
import { DesignModelAPI } from '../common/type';
import { DesignManageContext, IDesignActionEnum } from '../mconfig';
import { EditOutlined, EyeInvisibleOutlined, EyeOutlined } from '@ant-design/icons';
import ScrollBarLayout from '@/components/ScrollBarLayout';
import MyIcon from '@/components/MyIcon';
import pageStyles from '@/common/pageLayout.less';
import { ManageTreeTypeTitle } from './ManageTreeTypeTitle';
import { UpdatTreeModal } from './UpdatTreeModal';
import { treeloadMdicMapServuces } from '../services';

import _ from 'lodash';

export const ManageTreeTypeView: React.FC<DesignModelAPI.IManageTreeTypeView> = ({ typeTreeLoading, typeTreeData }) => {
  /**
   * 获取上下文
   */
  const { prefixCls, leftSelectKeys, leftExpandedKeys, leftAutoExpandParent, designDispatch, curRes } = useContext(
    DesignManageContext,
  );

  /**
   * 左侧树搜索数据
   */
  const [searchValueTree, setSearchValueTree] = useState<string>('');

  /**
   * 保存类型树数据
   */
  const [saveTypeTreeList, setSaveTypeTreeList] = useState<any[]>([]);

  useEffect(() => {
    if (typeTreeData && typeTreeData?.length > 0) {
      typeTreeData?.forEach((item: any) => {
        let oldTree: any = saveTypeTreeList?.find((itemOld: any) => {
          return item?.id == itemOld?.id;
        });
        if (oldTree && oldTree?.id) {
          item['children'] = oldTree?.children;
          designDispatch({
            type: IDesignActionEnum.TREETYPE_SELECTROW,
            payload: item,
          });
        }
      });
      setSaveTypeTreeList(typeTreeData);
    }
  }, [typeTreeData]);

  /**
   * 打开编辑新增弹框
   */
  const [updateModalObj, setUpdateModalObj] = useState<any>({
    isShowModal: false,
    checkRowObj: {},
  });

  /**
   * 显示新增编辑按钮
   * @param id
   * @param flag
   * @returns
   */
  const onTreeNodeMouseEnter = (id: string, flag: boolean) => {
    const ele = document.getElementById(id);
    if (flag) {
      return;
    } else if (ele) {
      ele.style.display = 'block';
    }
  };

  /**
   * 隐藏新增编辑按钮
   * @param id
   * @param flag
   * @returns
   */
  const onTreeNodeMouseLeave = (id: string, flag: boolean) => {
    const ele = document.getElementById(id);
    if (flag) {
      return;
    } else if (ele) {
      ele.style.display = 'none';
    }
  };

  /**
   * 是否显示 详情气泡
   */
  const [showPopoverID, setShowPopoverID] = useState<string>('');

  /**
   * 显示 隐藏 详情方法
   * @param openID  显示图标
   * @param closeID  闭合图标
   * @param showPopo  显示详情的 id
   * @param isOpen  true 显示     false 隐藏
   */
  const clickEyeDetail = (openID: string, closeID: string, showPopo: string, isOpen: boolean) => {
    const eleOpen = document.getElementById(openID);
    const eleClose = document.getElementById(closeID);
    if (eleOpen) {
      eleOpen.style.display = isOpen ? 'none' : 'inline-block';
    }
    if (eleClose) {
      eleClose.style.display = isOpen ? 'inline-block' : 'none';
    }
    setShowPopoverID(showPopo);
  };

  /**
   * 对树结构数据处理
   * @param data
   * @returns
   */
  const loopTreeData = (data: Record<string, any>[], isShowEdit: boolean): Record<string, any>[] => {
    return data?.map((item) => {
      const idName = item?.id + 'ShowBtnDesignTreeType';

      const detailEyeShow = item?.id + 'eyeShow' + Math.random();
      const detailEyeHiddren = item?.id + 'eyeHiddren' + Math.random();

      const showpopoverDom = item?.id + 'showpopoverDom';

      const flag = false;

      const content = (
        <div style={{ color: '#000000D9' }}>
          <p>
            相关工单：
            <span
              style={{
                color: item?.orderTypeName?.split('||')[1] || item?.fatherItem?.orderTypeName?.split('||')[1],
              }}
            >
              {item?.orderTypeName?.split('||')[0] || item?.fatherItem?.orderTypeName?.split('||')[0] || '--'}
            </span>
          </p>
          <p>
            相关业务：
            <span
              style={{
                color: item?.flowTypeName?.split('||')[1] || item?.fatherItem?.flowTypeName?.split('||')[1],
              }}
            >
              {item?.flowTypeName?.split('||')[0] || item?.fatherItem?.flowTypeName?.split('||')[0] || '--'}
            </span>
          </p>
          <p>
            表名：
            {item?.tableName || item?.fatherItem?.tableName || '--'}
          </p>
          <p>
            业务状态：
            <span
              style={{
                color: item?.stateTypeName?.split('||')[1] || item?.fatherItem?.stateTypeName?.split('||')[1],
              }}
            >
              {item?.stateTypeName?.split('||')[0] || item?.fatherItem?.stateTypeName?.split('||')[0] || '--'}
            </span>
          </p>
          <p>
            审核结果：
            <span
              style={{
                color: item?.checkTypeName?.split('||')[1] || item?.fatherItem?.checkTypeName?.split('||')[1],
              }}
            >
              {item?.checkTypeName?.split('||')[0] || item?.fatherItem?.checkTypeName?.split('||')[0] || '审核条件'}
            </span>
          </p>
        </div>
      );
      const text = item?.name;
      const nameLength = text?.length;
      const select = text?.search(searchValueTree);
      const searchLength = searchValueTree?.length;
      const afterStr = text?.slice(0, select);
      const selectStr = searchValueTree;
      const beforeStr = text?.slice(select + searchLength, nameLength);
      const titleTree =
        select > -1 && selectStr ? (
          <span className={pageStyles['over-flow-hidden']}>
            {afterStr}
            <span style={{ color: '#f50' }}>{selectStr}</span>
            {beforeStr}
          </span>
        ) : (
          <span className={pageStyles['over-flow-hidden']}>{item?.name}</span>
        );

      return {
        ...item,
        title: (
          <Popover
            placement="bottomLeft"
            content={content}
            title={item.name}
            color={'rgb(222 222 222)'}
            destroyTooltipOnHide={{ keepParent: false }}
            overlayClassName={pageStyles['tree-popover-detail']}
            open={showpopoverDom == showPopoverID ? true : false}
          >
            <div
              style={{
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'space-between',
              }}
              id={item?.id + 'DesignLeftTreeType'}
              onMouseEnter={() => {
                onTreeNodeMouseEnter(idName, flag);
              }}
              onMouseLeave={() => {
                onTreeNodeMouseLeave(idName, flag);
                clickEyeDetail(detailEyeShow, detailEyeHiddren, '', false);
              }}
            >
              <div
                style={{
                  display: 'flex',
                  alignItems: 'center',
                  width: '80%',
                }}
              >
                {item?.children ? <MyIcon type="icon-folder-open" /> : <MyIcon type="icon-folder1" />}
                &nbsp;
                {titleTree}
              </div>
              <div
                id={idName}
                style={{
                  whiteSpace: 'nowrap',
                  display: flag ? 'block' : 'none',
                }}
              >
                <a
                  style={{
                    display: 'inline-block',
                    marginRight: 8,
                  }}
                  id={detailEyeShow}
                  onClick={(e) => {
                    e?.stopPropagation();
                    clickEyeDetail(detailEyeShow, detailEyeHiddren, showpopoverDom, true);
                  }}
                >
                  <EyeOutlined />
                </a>
                <a
                  id={detailEyeHiddren}
                  style={{
                    display: 'none',
                    marginRight: 8,
                  }}
                  onClick={(e) => {
                    e?.stopPropagation();
                    clickEyeDetail(detailEyeShow, detailEyeHiddren, '', false);
                  }}
                >
                  <EyeInvisibleOutlined />
                </a>
                {isShowEdit && curRes?.['/activitiController/modelTypeEdit'] && (
                  <a
                    onClick={(e) => {
                      if (e && e.stopPropagation) {
                        e.stopPropagation();
                      }
                      setUpdateModalObj({
                        isShowModal: true,
                        checkRowObj: item,
                      });
                    }}
                  >
                    <EditOutlined />
                  </a>
                )}
              </div>
            </div>
          </Popover>
        ),
        key: item?.id,
        children: item?.children && item?.children?.length > 0 ? loopTreeData(item?.children, false) : [],
        isShowEdit: isShowEdit,
      };
    });
  };

  /**
   * 渲染的树结构数据
   */
  const categoryTreeData = useMemo(() => {
    return loopTreeData(saveTypeTreeList, true);
  }, [saveTypeTreeList, searchValueTree, leftSelectKeys, showPopoverID]);

  /**
   * 保存选中的值
   * @param checkedKeys
   * @param treeNodes
   */
  const onTreeSelect = (checkedKeys: any, treeNodes: any) => {
    if (checkedKeys && checkedKeys?.length > 0) {
      designDispatch({
        type: IDesignActionEnum.LEFTSELECT_KEYS,
        payload: checkedKeys,
      });

      if (treeNodes && treeNodes?.node && treeNodes?.node?.tableName) {
        designDispatch({
          type: IDesignActionEnum.TREETYPE_SELECTROW,
          payload: treeNodes?.node,
        });
        designDispatch({
          type: IDesignActionEnum.TREEDIC_SELECTROW,
          payload: {},
        });
      } else {
        const treeNodeIdList = treeNodes?.node?.id?.includes('_') ? treeNodes?.node?.id?.split('_') : treeNodes?.node?.id;
        let typeDataObj = categoryTreeData?.find((item: any) => {
          // return item?.flowType == treeNodes?.node?.typeID;
          return item?.id == treeNodeIdList?.[0];
        });
        designDispatch({
          type: IDesignActionEnum.TREEDIC_SELECTROW,
          payload: treeNodes?.node,
        });
        designDispatch({
          type: IDesignActionEnum.TREETYPE_SELECTROW,
          payload: typeDataObj ? typeDataObj : {},
        });
      }
    }
  };

  /**
   * 点击展开关闭树
   */
  const onTreeExpand = useCallback(
    (e, a) => {
      designDispatch({
        type: IDesignActionEnum.LEFTEXPANDED_KEYS,
        payload: e,
      });
      designDispatch({
        type: IDesignActionEnum.LEFTAUTO_PARENT,
        payload: false,
      });
    },
    [leftSelectKeys],
  );

  useEffect(() => {
    if (!(leftSelectKeys && leftSelectKeys?.length > 0) && typeTreeData && typeTreeData?.length > 0) {
      designDispatch({
        type: IDesignActionEnum.LEFTSELECT_KEYS,
        payload: [typeTreeData?.[0]?.id],
      });
      designDispatch({
        type: IDesignActionEnum.TREETYPE_SELECTROW,
        payload: typeTreeData?.[0],
      });
    }
  }, [leftSelectKeys, typeTreeData]);

  /**
   * 处理每个异步子节点保存最外层祖宗数据
   * @param dataList 异步子节点的数据
   * @param pItem 祖宗数据
   * @returns
   */
  const handChildList = (dataList: Record<string, any>[], pItem: Record<string, any>) => {
    dataList?.forEach((item: any, index: number) => {
      if (item && item?.children?.length > 0) {
        handChildList(item?.children, pItem);
      }
      dataList[index] = {
        ...item,
        fatherItem: pItem,
      };
    });
    return dataList;
  };

  /**
   * 处理异步数据
   * @param treeData 原有数据
   * @param parentKey 异步数据的 key
   * @param childList 异步的数据
   * @param selectKeys 异步数据的字段key
   */
  const handLoadDataList = (
    treeData: Record<string, any>[],
    parentKey: string,
    childList: Record<string, any>[],
    selectKeys: string,
  ) => {
    if (treeData?.length <= 0 || treeData == null || treeData == undefined) {
      return [];
    }
    treeData?.forEach((item, index) => {
      if (item?.children && item?.children?.length > 0) {
        handLoadDataList(item.children, item?.key, childList, 'id');
      }

      if (childList?.length > 0) {
        const childFirstId = childList?.[0]?.id;
        const flowPid: string = childFirstId?.split('_')?.[0];

        // if (item?.[`${selectKeys}`] == parentKey) {
        if (item?.id == flowPid) {
          let childrenArray: Record<string, any>[] = handChildList(childList, item);
          treeData[index] = {
            ...item,
            children: childrenArray,
          };
        }
      }
    });
    return treeData;
  };

  /**
   * 获取异步数据回调
   * @param res
   */
  const treeloadMdicMapCallback = (res: any) => {
    if (res && res?.msgFlag) {
      let [parentKey]: string[] = Object.keys(res?.obj);
      let loadChildList: Record<string, any>[] = res?.obj?.[parentKey];
      let NewTreeData: Record<string, any>[] = _.cloneDeep(
        handLoadDataList(saveTypeTreeList, parentKey, loadChildList, 'flowType'),
      );
      setSaveTypeTreeList(NewTreeData);
    }
  };

  /**
   * 获取异步数据
   */
  const { treeLoadMdicMapLoading, treeLoadMdicMapRun } = treeloadMdicMapServuces(treeloadMdicMapCallback);

  /**
   * 异步加载树数据
   */
  const loadDataTreeType = (treeNode: any) => {
    return new Promise((resolve: any) => {
      if (!treeNode?.tableName) {
        resolve();
        return;
      }
      treeLoadMdicMapRun({
        dicTypeIDs: treeNode?.flowType,
        prefixNum: `${treeNode?.id}_`,
      });
      resolve();
    });
  };

  return (
    <>
      <div className={prefixCls + 'flowCategoryStyle'}>
        <ManageTreeTypeTitle
          searchValueTree={searchValueTree}
          typeTreeData={saveTypeTreeList}
          saveSetSearchValue={(searchValue: string) => {
            setSearchValueTree(searchValue);
          }}
        />
        <div className={prefixCls + 'flowCategoryStyle-bodyContent'}>
          <Spin spinning={typeTreeLoading || treeLoadMdicMapLoading}>
            <ScrollBarLayout
              style={{
                padding: '0px 0px 5px',
              }}
            >
              {saveTypeTreeList && saveTypeTreeList?.length > 0 ? (
                <Tree
                  treeData={categoryTreeData}
                  blockNode={true}
                  selectedKeys={leftSelectKeys}
                  onSelect={onTreeSelect}
                  expandedKeys={leftExpandedKeys}
                  onExpand={onTreeExpand}
                  autoExpandParent={leftAutoExpandParent}
                  loadData={loadDataTreeType}
                />
              ) : (
                <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
              )}
            </ScrollBarLayout>
          </Spin>
        </div>
      </div>

      {/* body添加 类型弹框 */}
      {updateModalObj?.isShowModal && (
        <UpdatTreeModal
          visible={updateModalObj?.isShowModal}
          onClose={() => {
            setUpdateModalObj({
              isShowModal: false,
              checkRowObj: {},
            });
          }}
          checkRowObj={updateModalObj?.checkRowObj}
        />
      )}
    </>
  );
};
